package com.huawei.boss.ibatis;

import java.lang.reflect.Field;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.w3c.dom.Node;

import com.ibatis.common.xml.Nodelet;
import com.ibatis.common.xml.NodeletParser;
import com.ibatis.common.xml.NodeletUtils;
import com.ibatis.sqlmap.engine.builder.xml.SqlMapParser;
import com.ibatis.sqlmap.engine.builder.xml.XmlParserState;

/**
 * SqlMap配置解析逻辑，修改了ibatis在判读重复的sql的逻辑
 * 
 * @author c00170351
 */
public class DySqlMapParser extends SqlMapParser {
    private static final Logger LOGGER = Logger.getLogger(DySqlMapParser.class);

    private XmlParserState myState = null;

    public DySqlMapParser(XmlParserState state) {
        super(state);
        this.myState = state;
        resetSqlNodelets();
    }

    private void resetSqlNodelets() {
        try {
            Field f = SqlMapParser.class.getDeclaredField("parser");
            f.setAccessible(true);
            NodeletParser p = (NodeletParser) f.get(this);
            p.addNodelet("/sqlMap/sql", new Nodelet() {
                public void process(Node node) throws Exception {
                    Properties attributes = NodeletUtils.parseAttributes(node, myState.getGlobalProps());
                    String id = attributes.getProperty("id");
                    if (myState.isUseStatementNamespaces()) {
                        id = myState.applyNamespace(id);
                    }
                    myState.getSqlIncludes().put(id, node);
                }
            });
        } catch (SecurityException e) {
            LOGGER.error(e);
        } catch (IllegalArgumentException e) {
            LOGGER.error(e);
        } catch (NoSuchFieldException e) {
            LOGGER.error(e);
        } catch (IllegalAccessException e) {
            LOGGER.error(e);
        }
    }
}
